package cards;

import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class FileChooser extends JFrame implements ActionListener{
	private JMenuBar menuBar;
	private JMenu fileMenu;
	private JMenuItem openMenuItem, saveMenuItem;
	private ImageIcon card1, card2;
	
	public FileChooser(String title){
		super( title );
		
		setBounds(100, 100, 400, 300);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setLayout( null );
		
		
		card1 = new ImageIcon("src/cards/CardImages/01a.jpg");
		card2 = new ImageIcon("src/cards/CardImages/01b.jpg");
		
		// Set up the menu bar at the top of the window and
		//   add the File menu
		menuBar = new JMenuBar();		
		setJMenuBar( menuBar );
		fileMenu = new JMenu("File");	menuBar.add( fileMenu );
		openMenuItem = new JMenuItem("Open"); fileMenu.add(openMenuItem); 
		saveMenuItem = new JMenuItem("Save"); fileMenu.add(saveMenuItem);
		openMenuItem.addActionListener( this );
		saveMenuItem.addActionListener( this );
		
		setVisible( true );
	}

	private JFileChooser fc;

	public void actionPerformed(ActionEvent arg0) {
		if ( arg0.getSource().equals( openMenuItem ) ){
			fc = new JFileChooser( "Open" );
			int openValue = fc.showOpenDialog( this );
			if (openValue == JFileChooser.APPROVE_OPTION) {
	            try {
	            	FileInputStream file = new FileInputStream( fc.getSelectedFile() );
		            ObjectInputStream ois = new ObjectInputStream( file );
		            card1 = (ImageIcon) ois.readObject();
		            ois.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
	            repaint();
			}
		}
		if ( arg0.getSource().equals( saveMenuItem ) ){
			fc = new JFileChooser( "Save" );
			int saveValue = fc.showSaveDialog( this );
			if (saveValue == JFileChooser.APPROVE_OPTION) {
	            try {
		            FileOutputStream file = new FileOutputStream( fc.getSelectedFile() );
		            ObjectOutputStream oos = new ObjectOutputStream( file );
		            oos.writeObject( card1 );
		            oos.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
	            card1 = card2;
	            repaint();
			}
		}
	}

	public void paint(Graphics g){
		super.paint(g);
		
		g.drawImage( card1.getImage() , 50, 50, null );
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new FileChooser( "Choosing a file" );
	}
}
